package com.puzzlebazar.client.main.control;

import java.util.HashMap;


public abstract class NamedStateSubControllerImpl extends SubControllerImpl
	implements NamedStateController {

	private final SubStateTokenFactory tokenFactory;

	/**
	 * Creates a subcontroller with named states
	 * 
	 * @param parentController The parent of this sub controller
	 */
	protected NamedStateSubControllerImpl(GenericController parentController, SubStateTokenFactory tokenFactory) {
		super(parentController);
		
		this.tokenFactory = tokenFactory;
	}

	private final HashMap<String, NamedState> stateNameMap = 
		new HashMap<String, NamedState>();

	@Override
	public void addNamedState(String stateName, NamedState state) {
		assert( stateNameMap.get(stateName) == null );
		stateNameMap.put( stateName, state );
	}
	
	@Override
	public String getCurrentStateName() {
		assert( currentState instanceof NamedState );		
		return ((NamedState)currentState).getStateName();
	}

	@Override
	public void gotoStateNamed(String stateName) throws Exception {
		NamedState state = stateNameMap.get( stateName );

		if( state == null )
			throw new Exception( "Invalid history state token" );
		
		if( !leaveCurrentState() ) return;
		enterState( state );
	}

	@Override
	public String buildToken(String subStateName) {		
		return tokenFactory.buildToken(subStateName);
	}

	@Override
	public void enter() {
		return;
	}

	@Override
	public void exit() {
		return;
	}	
}
